package com.newland.zxy.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.newland.zxy.service.LoginService;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhangxuyuan
 * @Project: springsecurity
 * @Package com.newland.zxy.config
 * @date Date : 2021年02月08日 11:13
 */
public class MySecurityUtils {

    public static void responseForbiden(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        OutputStream out = response.getOutputStream();
        Map resultMap = new HashMap();
        resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
        resultMap.put("msg", "请登录！");
        out.write(new ObjectMapper().writeValueAsString(resultMap).getBytes("utf-8"));
        out.flush();
        out.close();
    }
    //检查token，返回储存在token中的user id
    public static String checkToken(String token)
    {
        try
        {
            Claims claims= Jwts.parserBuilder()
                    //设置解密算法
                    .setSigningKey(LoginService.key)
                    .build()
                    //解析token
                    .parseClaimsJws(token)
                    .getBody();
            String uid = claims.get("uid", String.class);
            return uid;

        }catch (ExpiredJwtException e)//超时异常
        {

            return null;
        }
        catch (JwtException e)//签名校验异常
        {

            return null;
        }
        catch (Exception e)
        {

            return null;
        }
    }


}
